package avicit.bdp.oss.utils.upload.utils.redis;

import avicit.bdp.oss.utils.upload.entity.OssUploadDto;
import avicit.bdp.oss.utils.upload.service.impl.OssUploadService;
import avicit.bdp.oss.utils.upload.utils.common.Constant;
import avicit.platform6.commons.utils.JsonHelper;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;

/**
 * @金航数码科技有限责任公司
 * @作者：developer
 * @邮箱：developer@avic-digital.com
 * @创建时间： 2020-12-09
 * @类说明：RedisKeyExpirationListener
 * @修改记录：
 * @注意事项：
 * @主要功能：Redis监听器
 */
@Component
public class OssRedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Autowired
    OssUploadService ossUploadService;

    private static final Logger logger = LoggerFactory.getLogger(OssRedisKeyExpirationListener.class);

    public OssRedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 键过期回调函数
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        if (StringUtils.isEmpty(expiredKey)) {
            return;
        }

        if (expiredKey.startsWith(Constant.OSS_EXPIRE_DEL_KEY)) {
            String[] strs = expiredKey.trim().split(Constant.AND);
            String jsonData = strs[1];

            OssUploadDto ossUploadDto = JsonHelper.getInstance().readValue(
                    jsonData,
                    new SimpleDateFormat(Constant.DATA_FORMAT),
                    new TypeReference<OssUploadDto>() {});

            logger.info("Redis中{}过期，开始清理碎片", expiredKey);

            ossUploadService.cleanUpExpiredData(ossUploadDto);
        }
    }
}
